#include "OnlineList.h"



/*
    初始化在线用户列表
*/
void initOnlineList()
{
    // 初始化在线列表 `头`
    // user of online list
    onlineList =  (node *)malloc(sizeof(node));
    if(onlineList == NULL)
    {
        perror("malloc");
        return;
    }
    // 管理员帐号：没用
    strcpy(onlineList->account,"110");
    onlineList->sockfd = 1;
    strcpy(onlineList->ingroup,"0");
    onlineList->next = NULL;
}

// 判断用户是否在线
bool isOnline(int fd)
{
    node* p = onlineList;
    while(p != NULL)
    {
        //判断用户是否在线
        if(p->sockfd == fd)	return true;
        p = p->next;
    }
    return false;
}

// 遍历在线用户列表
void TraverseOnlineList()
{
    node* p = onlineList;
    while(p != NULL)
    {
        printf("# TraverseOnlineList: %s: sockfd %d\n",p->account,p->sockfd);
        p = p->next;
    }
}

// 将用户添加到在线列表
void addOnlineList(char* acc,int fd,char ingroup)
{
    node* p = onlineList;
    while(p->next != NULL)	p = p->next;
    p->next = (node *)malloc(sizeof(node));

    if(p->next == NULL)
    {
        perror("malloc");
        return;
    }
    strcpy(p->next->account,acc);
    p->next->sockfd = fd;
    if(ingroup == 0)    strcpy(p->next->ingroup,"0");
    if(ingroup == 1)    strcpy(p->next->ingroup,"1");
    p->next->next = NULL;
//    TraverseOnlineList();printf("\n");
}


/*
    下线：从在线列表踢出
*/
void delOnlineList(int fd)
{
    node* father = onlineList;
    node* p = father->next;
    while(p != NULL)
    {
        if(p->sockfd == fd)
        {
            father->next = p->next;
            free(p);
            return;
        }
        father = p;
        p = p->next;
    }
}

// 查询在线列表 `用户名`
char* searchOnlineListAcc(int fd)
{
    node* p = onlineList;
    while(p != NULL)
    {
        if(p->sockfd == fd) return p->account;
        p = p->next;
    }
    return NULL;
}

/*
     查找某人对应的 `sockfd`
        input:  name - 帐号
        output: sockfd
*/
int searchOnlineListFd(char* name)
{
    node* p = onlineList;
    while(p != NULL)
    {
        if(strcmp(p->account,name) == 0) return p->sockfd;
        p = p->next;
    }
    return -1;
}


